package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.entry.search.PartSearch;
import com.drcoffee.drcoffeemall.mapper.CollectMapper;
import com.drcoffee.drcoffeemall.mapper.PartsMapper;
import com.drcoffee.drcoffeemall.mapper.ShoppingCartMapper;
import com.drcoffee.drcoffeemall.mapper.UserMapper;
import com.drcoffee.drcoffeemall.service.PartsService;
import com.drcoffee.drcoffeemall.util.DiscountedPriceUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class PartsServiceImpl implements PartsService {
    final
    PartsMapper partsMapper;

    final
    UserMapper userMapper;

    final
    RedisTemplate<String, Object> redisTemplate;

    final
    ShoppingCartMapper shoppingCartMapper;

    final
    CollectMapper collectMapper;

    public PartsServiceImpl(PartsMapper partsMapper, UserMapper userMapper, RedisTemplate<String, Object> redisTemplate, ShoppingCartMapper shoppingCartMapper, CollectMapper collectMapper) {
        this.partsMapper = partsMapper;
        this.userMapper = userMapper;
        this.redisTemplate = redisTemplate;
        this.shoppingCartMapper = shoppingCartMapper;
        this.collectMapper = collectMapper;
    }

    /**
     * Permission_id：用户类型【0：个人用户，1：企业用户，2：海外用户，3：企业用户（以个人价格算）】
     * 配件类型：【P:标准配件，N:非标准配件；注：非标准配件没有图片等一些信息】
     */
    @Override
    public Result getAttachment(String Token, PartSearch partSearch) {
        System.out.println("Token1111 = "+ Token);
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user == null) {
                return new Result(-2, "ERROR", "操作无效", null);
            }

            partSearch.setSearch("%" + partSearch.getSearch() + "%");
            PageHelper.startPage(partSearch.getCurrPage(), partSearch.getPageSize());
            List<Attachment> attachmentList;
            if (partSearch.getType().equals("N")) {
                String NonPartsSql = "";
                if (user.getPermission_id() == 1) {
                    NonPartsSql = ",b.dealer_price as price";
                } else if (user.getPermission_id() == 2){
                    NonPartsSql = ",b.overseas_price as price";
                }
                attachmentList = partsMapper.getNonParts(partSearch.getSearch(),NonPartsSql);
            } else {
                splice(user.getPermission_id(), partSearch);
                attachmentList = partsMapper.getAttachment(partSearch);
            }
            PageInfo<Attachment> attachmentPage = new PageInfo<>(attachmentList);
            // 计算折扣
            if (!attachmentPage.getList().isEmpty()) {
                // 判断该用户是否存在商品特殊价格
                List<SpecialPrice> specialPrice = null;
                // 用户类型为企业用户时需要判断该用户是否有被定义某个配件的特价
                if (user.getPermission_id() == 1) {
                    specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
                }
                for (Attachment attachment : attachmentPage.getList()) {
                    BigDecimal DiscountedbigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                    attachment.setDiscounted_price(DiscountedbigDecimal);
                    if (specialPrice != null) {
                        for (SpecialPrice special : specialPrice) {
                            if (Objects.equals(special.getPart_code(), attachment.getPart_code())) {
                                attachment.setDiscounted_price(special.getPrice());
                            }
                        }
                    }
                }
            }
            return new Result(1, "SUCCESS", "", attachmentPage);
        } catch (Exception e) {
            log.error("===================== getAttachment()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getAttachmentNoType(String Token, PartSearch partSearch) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user == null) {
                return new Result(-2, "ERROR", "操作无效", null);
            }
            partSearch.setSearch("%" + partSearch.getSearch() + "%");
            PageHelper.startPage(partSearch.getCurrPage(), partSearch.getPageSize());
            List<Attachment> attachmentList;
            splices(user.getPermission_id(), partSearch);
            attachmentList = partsMapper.getAttachmentNoType(partSearch);
            PageInfo<Attachment> attachmentPage = new PageInfo<>(attachmentList);
            // 计算折扣
            if (!attachmentPage.getList().isEmpty()) {
                // 判断该用户是否存在商品特殊价格
                List<SpecialPrice> specialPrice = null;
                // 用户类型为企业用户时需要判断该用户是否有被定义某个配件的特价
                if (user.getPermission_id() == 1) {
                    specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
                }
                for (Attachment attachment : attachmentPage.getList()) {
                    if (attachment.getPrice()!=null){
                        BigDecimal DiscountedbigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                        attachment.setDiscounted_price(DiscountedbigDecimal);
                        if (specialPrice != null) {
                            for (SpecialPrice special : specialPrice) {
                                if (Objects.equals(special.getPart_code(), attachment.getPart_code())) {
                                    attachment.setDiscounted_price(special.getPrice());
                                }
                            }
                        }
                    }
                }
            }
            return new Result(1, "SUCCESS", "", attachmentPage);
        } catch (Exception e) {
            log.error("===================== getAttachmentNoType()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getAttachmentMain(String Token, PartSearch partSearch) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user == null) {
                return new Result(-2, "ERROR", "操作无效", null);
            }
            partSearch.setSearch("%" + partSearch.getSearch() + "%");
            PageHelper.startPage(partSearch.getCurrPage(), partSearch.getPageSize());
            List<Attachment> attachmentList;
            splices(user.getPermission_id(), partSearch);
            attachmentList = partsMapper.getAttachmentMain(partSearch);
            PageInfo<Attachment> attachmentPage = new PageInfo<>(attachmentList);
            // 计算折扣
            if (!attachmentPage.getList().isEmpty()) {
                // 判断该用户是否存在商品特殊价格
                List<SpecialPrice> specialPrice = null;
                // 用户类型为企业用户时需要判断该用户是否有被定义某个配件的特价
                if (user.getPermission_id() == 1) {
                    specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
                }
                for (Attachment attachment : attachmentPage.getList()) {
                    if (attachment.getPrice()!=null){
                        BigDecimal DiscountedbigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                        attachment.setDiscounted_price(DiscountedbigDecimal);
                        if (specialPrice != null) {
                            for (SpecialPrice special : specialPrice) {
                                if (Objects.equals(special.getPart_code(), attachment.getPart_code())) {
                                    attachment.setDiscounted_price(special.getPrice());
                                }
                            }
                        }
                    }
                }
            }
            return new Result(1, "SUCCESS", "", attachmentPage);
        } catch (Exception e) {
            log.error("===================== getAttachmentMain()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    public void splices(Integer permission_id, PartSearch partSearch) {
        // 判断当前用户类型
//        Integer permission_id = userMapper.getUserType(partSearch.getAccount());
        if (permission_id == 0 || permission_id == 3) {
            // 0 零售 price
            partSearch.setPrice_type("b.price");
        } else if (permission_id == 1) {
            // 1 内销 dealer_price
            partSearch.setPrice_type("b.dealer_price as price");
        } else if (permission_id == 2) {
            // 2 外销 overseas_price
            partSearch.setPrice_type("b.overseas_price as price");
        }
    }

    public void splice(Integer permission_id, PartSearch partSearch) {
        // 判断当前用户类型
//        Integer permission_id = userMapper.getUserType(partSearch.getAccount());
        if (permission_id == 0 || permission_id == 3) {
            // 0 零售 price
            partSearch.setPrice_type("b.price");
        } else if (permission_id == 1) {
            // 1 内销 dealer_price
            partSearch.setPrice_type("b.dealer_price as price");
        } else if (permission_id == 2) {
            // 2 外销 overseas_price
            partSearch.setPrice_type("b.overseas_price as price");
        }

        if (Objects.equals(partSearch.getType(), "P")) {
            partSearch.setType("a.part_code like '7%'");
        } else if (Objects.equals(partSearch.getType(), "B")) {
            partSearch.setType("a.part_code like '8%'");
        } else if (Objects.equals(partSearch.getType(), "N")) {
            partSearch.setType("a.type = 'N'");
        }
    }

    @Override
    public Result getAttachmentById(String Token, String language, Integer dot_id) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            String price_type = "";

            Integer permission_id = user.getPermission_id();
            if (permission_id == 0 || permission_id == 3) {
                // 0 零售 price
                price_type = "b.price";
            } else if (permission_id == 1) {
                // 1 内销 dealer_price
                price_type = "b.dealer_price as price";
            } else if (permission_id == 2) {
                // 2 外销 overseas_price
                price_type = "b.overseas_price as price";
            }
            List<String> part_codes = partsMapper.getDots(dot_id);
            List<Attachment> attachmentList = new ArrayList<>();

            // 判断该用户是否存在商品特殊价格
            List<SpecialPrice> specialPrice = null;
            if (user.getPermission_id() == 1) {
                specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
            }

            // 计算折扣
            for (String partCode : part_codes) {
                Attachment attachment = partsMapper.getAttachmentById(language, partCode, price_type);
                BigDecimal discountedPrice = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                attachment.setDiscounted_price(discountedPrice);
                attachmentList.add(attachment);

                // 判断该用户是否存在商品特殊价格
                if (specialPrice != null) {
                    for (SpecialPrice special : specialPrice) {
                        if (Objects.equals(attachment.getPart_code(), special.getPart_code())) {
                            attachment.setDiscounted_price(special.getPrice());
                            attachmentList.add(attachment);
                        }
                    }
                }
            }
            return new Result(1, "SUCCESS", "", attachmentList);
        } catch (Exception e) {
            log.error("===================== getAttachmentById()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getAttachmentByCode(String Token, String part_code) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            String price_type = "";
            String language = "";

            Integer permission_id = user.getPermission_id();
            if (permission_id == 0 || permission_id == 3) {
                // 0 零售 price
                price_type = "b.price";
                language = "CN";
            } else if (permission_id == 1) {
                // 1 内销 dealer_price
                price_type = "b.dealer_price as price";
                language = "CN";
            } else if (permission_id == 2) {
                // 2 外销 overseas_price
                price_type = "b.overseas_price as price";
                language = "EN";
            }
            Attachment attachment = partsMapper.getAttachmentByCode(price_type, part_code, language);
            BigDecimal bigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
            attachment.setDiscounted_price(bigDecimal);

            // 判断该用户是否存在商品特殊价格
            // 特价条件：国内企业用户 && 没有折扣
            if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
                // 折扣为0
                List<SpecialPrice> specialPrice = null;
                if (user.getPermission_id() == 1) {
                    specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
                }
                if (specialPrice != null) {
                    for (SpecialPrice special : specialPrice) {
                        if (Objects.equals(attachment.getPart_code(), special.getPart_code())) {
                            attachment.setDiscounted_price(special.getPrice());
                        }
                    }
                }
            }
            return new Result(1, "SUCCESS", "", attachment);
        } catch (Exception e) {
            log.error("===================== getAttachmentByCode()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    @Override
    public Result getGiveaway(String Token, String language, Integer type, List<String> partCodes) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user == null) {
                throw new NullPointerException();
            }
            // 折扣不为0（享受折扣价）直接返回不参与满送
            if (user.getPermission_id() != 1 || (user.getDiscount_one().compareTo(BigDecimal.ZERO) != 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) != 0)) {
                return new Result(2, "SUCCESS", "No freebies", null);
            }
            String source = type == 1 ? "t_cart" : "t_collect";
            // 查询出该用户参与特价的配件料号list
            List<String> init_specialPrice = partsMapper.getSpecialPricePartCodes(user.getErp_code());
            // (筛出特价商品)-删除属于特价的配件料号
            partCodes.removeAll(init_specialPrice);
            // 1.查询满足满赠条件的配件
            List<Giveaway> satisfyGiveawayList = null;
            if (!partCodes.isEmpty()) {
                satisfyGiveawayList = partsMapper.getPartCodesBySatisfyGiveaway(user.getAccount(), source, partCodes);
            }
            if (satisfyGiveawayList == null || satisfyGiveawayList.isEmpty()) {
                // 没有参与满赠的配件
                return new Result(2, "SUCCESS", "No freebies", null);
            }

            // 有参与满赠的配件
            // 2.拿到赠送的配件料号list
            List<String> SatisfyGiveawayPartCodes = satisfyGiveawayList.stream()
                    .map(Giveaway::getG_code)
                    .collect(Collectors.toList());

            // 3.根据赠送的配件料号查询配件信息
            List<Attachment> giveawayPartList = partsMapper.getPartsByCodes("0 as price", language, SatisfyGiveawayPartCodes);

            // 3.根据来源(type)查询数量(购物车、收藏)
            List<? extends ProductQuantity> targetList = (type == 1) ? shoppingCartMapper.getCartByAccountAndPartCodes(user.getAccount(), SatisfyGiveawayPartCodes)
                    : (type == 2) ? collectMapper.getCollectByAccountAndPartCodes(user.getAccount(), SatisfyGiveawayPartCodes)
                    : null;
            if (targetList != null) {
                for (ProductQuantity target : targetList) {
                    // Giveaway：满赠条件
                    Giveaway targetGiveaway = satisfyGiveawayList.stream()
                            .filter(giveaway -> giveaway.getG_code().equals(target.getPart_code()))
                            .findFirst()
                            .orElse(null);
                    if (targetGiveaway != null) {
                        giveawayPartList = giveawayPartList.stream()
                                .map(attachment -> {
                                    if (target.getPart_code().equals(attachment.getPart_code())) {
                                        attachment.setQuantity((target.getQuantity() / targetGiveaway.getFull()) * targetGiveaway.getGift());
                                    }
                                    return attachment;
                                })
                                .collect(Collectors.toList());
                    }
                }
                return new Result(1, "SUCCESS", "", giveawayPartList);
            } else {
                return new Result(-1, "WARN", "Data is null", null);
            }
        } catch (Exception e) {
            log.error("===================== getGiveaway()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }
}
